const mysql = require('mysql2/promise');
const dbConfig = require('../config/db.config');
const Logger = require('../utils/logger');

class DatabaseService {
  constructor() {
    try {
      this.pool = mysql.createPool({
        host: dbConfig.host,
        user: dbConfig.user,
        password: dbConfig.password,
        database: dbConfig.database,
        port: dbConfig.port,
        connectionLimit: dbConfig.connectionLimit,
        waitForConnections: true,
        queueLimit: 0
      });
      Logger.info('DatabaseService', '数据库连接池已创建');
    } catch (error) {
      Logger.error('DatabaseService', '创建数据库连接池失败', error);
      throw error;
    }
  }

  // 添加无人机
  async addDrone(droneId, name = null) {
    try {
      const [result] = await this.pool.execute(
        'INSERT INTO drones (id, name) VALUES (?, ?) ON DUPLICATE KEY UPDATE name = ?',
        [droneId, name, name]
      );
      console.log(`无人机 ${droneId} 已添加/更新到数据库`);
      return { success: true, insertId: result.insertId };
    } catch (error) {
      console.error('添加无人机时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 删除无人机
  async deleteDrone(droneId) {
    try {
      // 先更新相关流的状态为非活动
      const [updateResult] = await this.pool.execute(
        'UPDATE streams SET status = "inactive", end_time = CURRENT_TIMESTAMP WHERE drone_id = ? AND status = "active"',
        [droneId]
      );
      
      // 删除无人机记录
      const [deleteResult] = await this.pool.execute(
        'DELETE FROM drones WHERE id = ?',
        [droneId]
      );
      
      console.log(`无人机 ${droneId} 已从数据库中删除，影响 ${deleteResult.affectedRows} 行`);
      
      return { 
        success: true, 
        affectedRows: deleteResult.affectedRows,
        streamsUpdated: updateResult.affectedRows
      };
    } catch (error) {
      console.error('删除无人机时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 获取所有无人机
  async getAllDrones() {
    try {
      const [rows] = await this.pool.execute('SELECT * FROM drones ORDER BY created_at DESC');
      console.log(`从数据库中检索到 ${rows.length} 个无人机`);
      return { success: true, data: rows };
    } catch (error) {
      console.error('获取无人机时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 根据ID获取无人机
  async getDroneById(droneId) {
    try {
      const [rows] = await this.pool.execute('SELECT * FROM drones WHERE id = ?', [droneId]);
      console.log(`无人机 ${droneId} 查找结果: ${rows.length > 0 ? '找到' : '未找到'}`);
      return { success: true, data: rows[0] || null };
    } catch (error) {
      console.error('获取无人机时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 更新无人机状态
  async updateDroneStatus(droneId, status) {
    try {
      const [result] = await this.pool.execute(
        'UPDATE drones SET status = ? WHERE id = ?',
        [status, droneId]
      );
      console.log(`无人机 ${droneId} 状态已更新，影响 ${result.changedRows} 行`);
      return { success: true, changedRows: result.changedRows };
    } catch (error) {
      console.error('更新无人机状态时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 添加或更新流记录（包含源地址）
  async addOrUpdateStream(droneId, streamName, rtmpUrl, sourceUrl = null, sourceType = null) {
    try {
      // 先检查是否已有该无人机的活动流
      const [existingRows] = await this.pool.execute(
        'SELECT id FROM streams WHERE drone_id = ? AND status = "active"',
        [droneId]
      );
      
      if (existingRows.length > 0) {
        // 更新现有记录
        const streamId = existingRows[0].id;
        const [updateResult] = await this.pool.execute(
          'UPDATE streams SET stream_name = ?, rtmp_url = ?, source_url = ?, source_type = ?, start_time = CURRENT_TIMESTAMP WHERE id = ?',
          [streamName, rtmpUrl, sourceUrl, sourceType, streamId]
        );
        Logger.info('DatabaseService', `无人机 ${droneId} 的流已更新，流ID: ${streamId}`);
        return { success: true, insertId: streamId, updated: true };
      } else {
        // 插入新记录
        const [result] = await this.pool.execute(
          'INSERT INTO streams (drone_id, stream_name, rtmp_url, source_url, source_type) VALUES (?, ?, ?, ?, ?)',
          [droneId, streamName, rtmpUrl, sourceUrl, sourceType]
        );
        Logger.info('DatabaseService', `无人机 ${droneId} 的流已添加，ID 为 ${result.insertId}`);
        return { success: true, insertId: result.insertId, updated: false };
      }
    } catch (error) {
      Logger.error('DatabaseService', '添加/更新流时出错', error);
      return { success: false, error: error.message };
    }
  }

  // 添加流记录（兼容性方法，调用addOrUpdateStream）
  async addStream(droneId, streamName, rtmpUrl, sourceUrl = null, sourceType = null) {
    return await this.addOrUpdateStream(droneId, streamName, rtmpUrl, sourceUrl, sourceType);
  }

  // 获取无人机的所有流
  async getStreamsByDroneId(droneId) {
    try {
      const [rows] = await this.pool.execute(
        'SELECT * FROM streams WHERE drone_id = ? ORDER BY start_time DESC',
        [droneId]
      );
      console.log(`为无人机 ${droneId} 检索到 ${rows.length} 个流`);
      return { success: true, data: rows };
    } catch (error) {
      console.error('获取流时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 获取无人机的活动流
  async getActiveStreamByDroneId(droneId) {
    try {
      const [rows] = await this.pool.execute(
        'SELECT * FROM streams WHERE drone_id = ? AND status = "active" ORDER BY start_time DESC LIMIT 1',
        [droneId]
      );
      console.log(`为无人机 ${droneId} 检索到 ${rows.length} 个活动流`);
      return { success: true, data: rows[0] || null };
    } catch (error) {
      console.error('获取活动流时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 获取所有活动流（用于恢复）
  async getAllActiveStreams() {
    try {
      const [rows] = await this.pool.execute(
        'SELECT * FROM streams WHERE status = "active" AND source_url IS NOT NULL ORDER BY created_at DESC'
      );
      Logger.info('DatabaseService', `检索到 ${rows.length} 个活动流配置`);
      return { success: true, data: rows };
    } catch (error) {
      Logger.error('DatabaseService', '获取活动流时出错', error);
      return { success: false, error: error.message };
    }
  }

  // 更新流状态
  async updateStreamStatus(streamId, status) {
    try {
      const [result] = await this.pool.execute(
        'UPDATE streams SET status = ?, end_time = ? WHERE id = ?',
        [status, status === 'inactive' ? new Date() : null, streamId]
      );
      console.log(`流 ${streamId} 状态已更新，影响 ${result.changedRows} 行`);
      return { success: true, changedRows: result.changedRows };
    } catch (error) {
      console.error('更新流状态时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 添加流转发记录
  async addStreamForward(streamId, targetRtmpUrl) {
    try {
      const [result] = await this.pool.execute(
        'INSERT INTO stream_forwards (stream_id, target_rtmp_url) VALUES (?, ?)',
        [streamId, targetRtmpUrl]
      );
      console.log(`流 ${streamId} 的转发记录已添加，ID 为 ${result.insertId}`);
      return { success: true, insertId: result.insertId };
    } catch (error) {
      console.error('添加流转发记录时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 获取流的所有转发记录
  async getStreamForwards(streamId) {
    try {
      const [rows] = await this.pool.execute(
        'SELECT * FROM stream_forwards WHERE stream_id = ? ORDER BY created_at DESC',
        [streamId]
      );
      console.log(`为流 ${streamId} 检索到 ${rows.length} 个转发记录`);
      return { success: true, data: rows };
    } catch (error) {
      console.error('获取流转发记录时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 更新流转发状态
  async updateStreamForwardStatus(forwardId, status) {
    try {
      const [result] = await this.pool.execute(
        'UPDATE stream_forwards SET status = ? WHERE id = ?',
        [status, forwardId]
      );
      console.log(`流转发记录 ${forwardId} 状态已更新，影响 ${result.changedRows} 行`);
      return { success: true, changedRows: result.changedRows };
    } catch (error) {
      console.error('更新流转发状态时出错:', error);
      return { success: false, error: error.message };
    }
  }

  // 测试数据库连接
  async testConnection() {
    try {
      const connection = await this.pool.getConnection();
      Logger.info('DatabaseService', '数据库连接成功');
      connection.release();
      return { success: true };
    } catch (error) {
      Logger.error('DatabaseService', '数据库连接失败', error);
      return { success: false, error: error.message };
    }
  }

  // 关闭连接池
  async close() {
    try {
      await this.pool.end();
      Logger.info('DatabaseService', '数据库连接池已关闭');
    } catch (error) {
      Logger.error('DatabaseService', '关闭数据库连接池失败', error);
    }
  }
}

module.exports = DatabaseService;